extends CharacterBody2D

var movement_speed : float = 150
# Health改变的时候改变血条
var health : float = 100:
	set(value):
		health = max(value,0)
		%Health.value = value
var max_health : float = 100:
	set(value):
		max_health = value
		%Health.max_value = max_health
# 回复属性
var recovery : float = 0
# 护甲属性
var armor : float = 0
# 伤害倍数
var might : float = 1
# 攻击范围
var area : float = 0
# 拾取泛微
var magent : float = 0:
	set(value):
		magent = value
		%magnet_body.shape.radius = 50 + value
# 经验值倍率
var growth : float = 1

#最近的怪物节点
var nearest_enemy : CharacterBody2D
#最近的怪物距离,默认为无限远
var nearest_enemy_distance : float = 150 + area

var XP : float = 0:
	set(value):
		XP = value
		%XP.value = value
		
var total_xp : float = 0:
	set(value):
		total_xp = value
		
var level : int = 1:
	set(value):
		level = value
		%Level.text = "lv." + str(value)
		# 显示武器升级弹框
		%Options.show_option()
		if level >= 3:
			%XP.max_value = 20
		if level >= 7:
			%XP.max_value = 40
			
func _ready() -> void:
	magent = 100
	
func _physics_process(delta: float) -> void:
	# 敌人血量见底的时候,会被释放掉,所以这里要检查这个对象是否可用
	if is_instance_valid(nearest_enemy):
		nearest_enemy_distance = nearest_enemy.separation
	else:
		nearest_enemy_distance = 150 + area
		nearest_enemy = null
	velocity = Input.get_vector("left","right","up","down") * movement_speed
	move_and_collide(velocity * delta)
	check_XP()
	health += recovery * delta

# 玩家受到攻击
func take_damage(amount)->void:
	health -= max(amount - armor,0)

func _on_self_damage_body_entered(body) -> void:
	take_damage(body.damage)
	
func _on_timer_timeout() -> void:
	%self_damage_body.set_deferred("disabled",true)
	%self_damage_body.set_deferred("disabled",false)

# 获取经验值
func gain_XP(amount:float)->void:
	XP += amount * growth
	total_xp += amount * growth

# 经验满后,重置经验条位置
func check_XP() -> void:
	if XP > %XP.max_value:
		# 经验升级后,重置下一个经验条位置
		XP -= %XP.max_value
		level += 1

#检测拾取物是否碰撞玩家捡东西的碰撞体(Magnet)
func _on_magnet_body_entered(_area: Node2D) -> void:
	if _area.has_method("follow"):
		_area.follow(self)
	
